package io.bhex.app.market.ui;

/*
 * *******************************************************************
 * @项目名称: android Android
 * @文件名称:
 * @Date: 2019/1/30
 * @Author: chenjun
 * @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 * *******************************************************************
 */


import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.market.adapter.MarketListMultiAdapter;
import io.bhex.app.market.event.ItemClickStatusListener;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.trade.ui.ContractTradeFragment;
import io.bhex.app.utils.AnimalUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.JsonUtils;
import io.bhex.baselib.utils.LongLog;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.enums.COIN_TYPE;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FuturensBaseToken;
import io.bhex.sdk.quote.bean.NewCoinPairListBean;
import io.bhex.sdk.quote.bean.OptionCategoryBean;
import io.bhex.sdk.quote.bean.QuoteBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;

/**
 * ================================================
 * 描   述：交易选择币对
 * ================================================
 */

@SuppressLint("ValidFragment")
public class OptionCoinDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener, View.OnClickListener, ItemClickStatusListener {
    private int mTradeType = 0;
    private DialogInterface.OnDismissListener mOnDismissListener;
    private String mSymbolId = "";
    private CoinPairBean mCoinPairBean;
    private ImageView closeSearch;
    private EditText editSearch;
    private ViewPager viewPager;
    private RecyclerView recyclerView;
    private SkinTabLayout tab;
    private TopBar topBar;
    private RelativeLayout searchRela;
    private ArrayList<Pair<String, QuoteTokensBean.TokenItem>> items;
    private MarketAdapter marketAdapter;
    private String currentExchangeId;
    private MarketListMultiAdapter adapter;
    private RelativeLayout rootView;
    private View divider;
    private List<CoinPairBean> coinPairList;
    private RelativeLayout bottomRela;
    private boolean isTouching =false;
    private static final int TOUCH_DOWN_NOTIFY = 1; //触摸down
    private static final int TOUCH_UP_OR_CANCEL_NOTIFY = 2; //触摸up 或者cancel
    private List<CoinPairBean> mData;

    /**
     * https://www.jianshu.com/p/8df58655bfe3
     * Fragment必须有一个无参public的构造函数，否则在数据恢复的时候,会报crash
     */
    public OptionCoinDialogFragment() {

    }

    @SuppressLint("ValidFragment")
    public OptionCoinDialogFragment(int tradeType, CoinPairBean coinPairBean, DialogInterface.OnDismissListener onDismissListener) {
        mTradeType = tradeType;
        mCoinPairBean = coinPairBean;
        if (mCoinPairBean != null) {
            mSymbolId = mCoinPairBean.getSymbolId();
        }
        mOnDismissListener = onDismissListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这句代码的意思是让dialogFragment弹出时沾满全屏
//        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.popDialogStyle);
//        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Light);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        getDialog().setCanceledOnTouchOutside(false);
//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉Dialog标题
        View view = inflater.inflate(R.layout.pop_coinpair_layout, container, false);
        //让DialogFragment的背景为透明
        Window window = getDialog().getWindow();

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //window.setBackgroundDrawable(new BitmapDrawable(mBlurBg));
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.MATCH_PARENT;
//        wlp.height = PixelUtils.getScreenHeight();
//        window.getDecorView().setPadding(0,0,0,0);
        window.setAttributes(wlp);
        initView(view);
        initEvent();
        return view;
    }

    //初始化view
    private void initView(View view) {
        rootView = view.findViewById(R.id.rootView);
        bottomRela = view.findViewById(R.id.bottomRela);
        closeSearch = view.findViewById(R.id.close_search);
        editSearch = view.findViewById(R.id.edit_search);

        viewPager = view.findViewById(R.id.clViewPager);
        recyclerView = view.findViewById(R.id.clRecyclerView);
        tab = view.findViewById(R.id.tabCoin);
        tab.setTabTextColors(SkinColorUtil.getDark(this.getActivity()), getResources().getColor(R.color.blue));
        divider = view
                .findViewById(R.id.divider);
        topBar = view.findViewById(R.id.topBar);
        topBar.setTitleRightDrawable(R.mipmap.icon_drawer);
        AnimalUtils.rotateyAnimRun(topBar.getTitleIcon(), 0.0f, 180.0f);
        if (mCoinPairBean != null) {
            String call = "";
            topBar.setLeftImgVisible(View.GONE);
            if (mCoinPairBean.baseTokenOption != null) {
                if (KlineUtils.isOptionCall(mCoinPairBean.baseTokenOption.isCall)) {
                    call = getString(R.string.string_option_call);
                    topBar.setLeftTextAndBackGround(call, R.style.Mini_Green, R.drawable.bg_corner_rect_green);
                } else {
                    call = getString(R.string.string_option_put);
                    topBar.setLeftTextAndBackGround(call, R.style.Mini_Red, R.drawable.bg_corner_rect_red);
                }
            }
            DebugLog.d("OptionCoinDialogFragment===>:","symbolName=="+mCoinPairBean.getSymbolName());
            topBar.setTitle(mCoinPairBean.getSymbolName());
            topBar.setTitleAppearance(R.style.BodyL_Dark_Bold);
        }
        editSearch = view.findViewById(R.id.edit_search);
        closeSearch = view.findViewById(R.id.close_search);
        searchRela = view.findViewById(R.id.rela_search);

        getCoinPairList();
    }

    private void initEvent() {
        bottomRela.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.closeKeybord(editSearch, getActivity());
                closePop(false);
            }
        });
        topBar.setTitleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtil.hideKeyboard(getActivity());
                closePop(false);
            }
        });
        closeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (items.size() > 1)
                    tab.setVisibility(View.VISIBLE);
                divider.setVisibility(View.VISIBLE);
                topBar.setVisibility(View.VISIBLE);
                searchRela.setVisibility(View.GONE);
                editSearch.setText("");
                filterList.clear();
                changePage(getCurrentTabId());

                AnimalUtils.alphaAnimRun(topBar, true ? 0.0f : 1.0f, true ? 1.0f : 0.0f);
//                AnimalUtils.scaleAnimRun(searchRela, false ? 0.0f : 1.0f, false ? 1.0f : 0.0f);
                KeyBoardUtil.closeKeybord(editSearch, getActivity());
            }
        });

//        topBar.setRightImg(R.mipmap.icon_search);
        //屏蔽期权搜索功能
//        topBar.setRightOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                topBar.setVisibility(View.GONE);
//                searchRela.setVisibility(View.VISIBLE);
//                divider.setVisibility(View.GONE);
//                if (adapter != null) {
//                    adapter.setNewData(null);
//                }
//                AnimalUtils.alphaAnimRun(topBar, false ? 0.0f : 1.0f, false ? 1.0f : 0.0f);
////                AnimalUtils.scaleAnimRun(searchRela, true ? 0.0f : 1.0f, true ? 1.0f : 0.0f);
//                //KeyBoardUtil.openKeybord(editSearch, getActivity());
//
//                editSearch.setFocusable(true);
//                editSearch.setFocusableInTouchMode(true);
//            }
//        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    editSearch.setTextAppearance(getActivity(), CommonUtil.isBlackMode() ? R.style.H4_Grey_No_Bold_night : R.style.H4_Grey_No_Bold);
                    editSearch.setHintTextColor(SkinColorUtil.getDark50(OptionCoinDialogFragment.this.getActivity()));
                } else {
                    editSearch.setTextAppearance(getActivity(), CommonUtil.isBlackMode() ? R.style.H4_Dark_night : R.style.H4_Dark);
                    editSearch.setHintTextColor(SkinColorUtil.getDark50(OptionCoinDialogFragment.this.getActivity()));
                }
                searchCoin(s.toString().trim());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        QuoteApi.UnSubTickers();
        QuoteApi.UnSubTickers();
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss(dialog);
        }
    }

    private ArrayList<CoinPairBean> filterList = new ArrayList<>();

    /**
     * 搜索币种
     *
     * @param searchContent
     */
    private void searchCoin(String searchContent) {
        if (adapter == null)
            return;
        if (TextUtils.isEmpty(searchContent)) {
            adapter.setNewData(null);
            return;
        }
        if (coinPairList != null) {
            filterList.clear();
            for (CoinPairBean coinPairBean : coinPairList) {
                if (isMatch(searchContent, coinPairBean)) {
                    filterList.add(coinPairBean);
                }

            }
            adapter.setNewData(filterList);
        }
    }

    private boolean isMatch(String searchContent, CoinPairBean coinPairBean) {
        String quoteTokenName = coinPairBean.getQuoteTokenName();
        String baseTokenName = coinPairBean.getBaseTokenName();
        String symbolNName = coinPairBean.getSymbolName();
        if (!TextUtils.isEmpty(searchContent)) {
            searchContent = searchContent.toUpperCase();
        }
        if (!TextUtils.isEmpty(baseTokenName)) {
            baseTokenName = baseTokenName.toUpperCase();
            if (baseTokenName.contains(searchContent)) {
                return true;
            }
        }
        if (!TextUtils.isEmpty(quoteTokenName)) {
            quoteTokenName = quoteTokenName.toUpperCase();
            return quoteTokenName.contains(searchContent);
        }

        if (!TextUtils.isEmpty(symbolNName)) {
            symbolNName = symbolNName.toUpperCase();
            return symbolNName.contains(searchContent);
        }


        return false;
    }

    public void closePop(boolean isNeedCancelSub) {
        if (getDialog().isShowing()) {
            dismiss();
        }
        /*if (isNeedCancelSub) {

            QuoteApi.UnSubTickers();
        }*/
    }

    /**
     * 市场fragment
     *
     * @param tabMap
     */
    private void initFragmentTab(LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap) {

        if (items == null || items.size() < 1) {

            items = new ArrayList<>();
            for (String tabId : tabMap.keySet()) {
                QuoteTokensBean.TokenItem tokenItem = tabMap.get(tabId);
                String first = tokenItem.getTabName();
                List<String> ExploretokenList = SymbolDataManager.GetInstance().getExploreToken();
                if (ExploretokenList != null && ExploretokenList.size() > 0) {
                    for (String explore : ExploretokenList
                    ) {
                        if (!TextUtils.isEmpty(first) && first.contains(explore)) {
                            first = getString(R.string.string_exploretoken);
                        }
                    }
                }
                items.add(new Pair<String, QuoteTokensBean.TokenItem>(first, tokenItem));
            }
            marketAdapter = new MarketAdapter(getChildFragmentManager());
            viewPager.setAdapter(marketAdapter);
            tab.setupWithViewPager(viewPager);
            tab.setTabMode(TabLayout.MODE_SCROLLABLE);
            tab.setTabGravity(TabLayout.GRAVITY_CENTER);

            CommonUtil.setUpIndicatorWidthByReflex2(tab, 15, 15);
            viewPager.addOnPageChangeListener(this);
            if (items.size() < 1){
                tab.setVisibility(View.GONE);
            }else{
                viewPager.setCurrentItem(0);
            }
        }
    }

    public void showTabOfQuoteTokens(LinkedHashMap<String, QuoteTokensBean.TokenItem> tokens) {
        initFragmentTab(tokens);
    }

    /**
     * 默认返回自选
     *
     * @return tokenId作为tabId
     */
    public String getCurrentTabId() {
        if (marketAdapter != null) {
            return marketAdapter.TokenID(viewPager.getCurrentItem());
        }
        return "";
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        String tabId = "";
        if (marketAdapter != null) {
            tabId = marketAdapter.TokenID(viewPager.getCurrentItem());
        }

        changePage(tabId);

    }


    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case TOUCH_DOWN_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
                case TOUCH_UP_OR_CANCEL_NOTIFY:
                    isTouching = false;
                    showMarket(mData);
                    break;
            }
        }
    };

    @Override
    public void onItemStatusListener(boolean isClick) {
        if (isClick) {
            isTouching = true;
            mHandler.sendEmptyMessageDelayed(TOUCH_DOWN_NOTIFY,1000);
        }else{
            mHandler.sendEmptyMessageDelayed(TOUCH_UP_OR_CANCEL_NOTIFY,200);
        }
    }

    private class MarketAdapter extends FragmentPagerAdapter {

        public MarketAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }

        public String TokenID(int position) {
            String tokenId = "";
            if (items.get(position).second != null)
                tokenId = items.get(position).second.getTokenId();
            return tokenId;
        }


    }

    //创建tab 数据Map
    LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = new LinkedHashMap<>();

    /**
     * 创建tab数据集
     *
     * @param response
     */
    private LinkedHashMap<String, QuoteTokensBean.TokenItem> createTabMap(List<QuoteTokensBean.TokenItem> response) {

        if (response != null) {

            tabMap.clear();

            for (QuoteTokensBean.TokenItem tokenItem : response) {
                DebugLog.e("MAP", tokenItem.getTokenId() + tokenItem.getTokenFullName());
                tokenItem.setTabName(tokenItem.getTokenName());
                tabMap.put(tokenItem.getTokenId(), tokenItem);
            }
        }
        return tabMap;
    }

    /**
     * 获取币对列表
     */
    public void getCoinPairList() {
        SymbolDataManager.GetInstance().getNewCoinPairList(new SimpleResponseListener<NewCoinPairListBean>() {

            @Override
            public void onSuccess(NewCoinPairListBean response) {
                super.onSuccess(response);

                //LongLog.loge("ABBB====>NewCoinPairListBean:","json:"+ JsonUtils.toJson(response));

                if (CodeUtils.isSuccess(response, true)) {
                    if (mTradeType == ContractTradeFragment.TAB_OPTION) {
                        if (response.optionQuoteToken != null) {
                            LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = createTabMap(response.optionQuoteToken);
                            showTabOfQuoteTokens(tabMap);
                            //getCoinPairList();
                            handCoinPairListData(response.optionSymbol);
                            getRealTimeData();
                        }

                    } else if (mTradeType == ContractTradeFragment.TAB_FUTURES) {
                        if (response.futuresUnderlying != null) {
                            LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = createTabMapOfFutures(response.futuresUnderlying);
                            showTabOfQuoteTokens(tabMap);
                            //getCoinPairList();
                            handCoinPairListData(response.futuresSymbol);
                            getRealTimeData();
                        }

                    }

                }
            }

        });

    }

    protected LinkedHashMap<String, QuoteTokensBean.TokenItem> createTabMapOfFutures(List<OptionCategoryBean> tabs) {

        if (tabs != null) {

            tabMap.clear();

            for (OptionCategoryBean tabItem : tabs) {
                DebugLog.e("MAP", tabItem.getId() + tabItem.getName());
                QuoteTokensBean.TokenItem tokenItem = new QuoteTokensBean.TokenItem();
                tokenItem.setTabName(tabItem.getName());
                tokenItem.setTokenId(tabItem.getId());
                tokenItem.setTabName(tabItem.getName());
                tokenItem.setTokenName(tabItem.getName());
                tokenItem.setTokenFullName(tabItem.getName());
                tabMap.put(tokenItem.getTokenId(), tokenItem);
            }
        }
        return tabMap;
    }

    /**
     * 拼接行情参数
     *
     * @return
     */
    private String getSymbolsListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : tabMap.keySet()) {
            if (!key.equals(AppData.KEY_FAVORITE)) {//刷出自选,因为其他的列表已经包括
                QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
                if (tokenItem != null) {
                    HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                    if (coinPairMap != null) {
                        if (!coinPairMap.isEmpty()) {
                            for (String keyOfCoin : coinPairMap.keySet()) {
                                CoinPairBean coinPairBean = coinPairMap.get(keyOfCoin);
                                if (coinPairBean != null) {
                                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                                    if (stringBuffer.toString().length() > 0) {
                                        stringBuffer.append("," + symbol);
                                    } else {
                                        stringBuffer.append(symbol);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return stringBuffer.toString();
    }

    public void getRealTimeData() {
        String symbolsListStr = getSymbolsListStr();
        QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (!isVisible() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        handleSocketMarketList(data);
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    private void handleSocketMarketList(TickerBean tickerBean) {
        String currentTabId = getCurrentTabId();
        QuoteTokensBean.TokenItem currentTokenItem = tabMap.get(currentTabId);

        for (String key : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
            if (tokenItem != null) {
                HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                if (coinPairMap != null) {
                    for (String coinKey : coinPairMap.keySet()) {
                        CoinPairBean coinPairBean = coinPairMap.get(coinKey);
                        String symbol = coinPairBean.getSymbolId();
                        String symbolTicker = tickerBean.getS();
                        if (symbol.equals(symbolTicker)) {
                            coinPairBean.setTicker(tickerBean);
                            if (currentTokenItem == tokenItem)
                                notifyCoinPairListDataChange(tabMap);
                        }

                    }

                }

            }
        }
    }

    /**
     * 处理币对列表数据
     *
     * @param listBean
     */
    private void handCoinPairListData(List<CoinPairBean> listBean) {
        coinPairList = listBean;
        if (coinPairList != null && !coinPairList.isEmpty()) {

            for (CoinPairBean coinPairBean : coinPairList) {
                if (mTradeType == ContractTradeFragment.TAB_OPTION) {
                    CoinPairBean.BaseTokenOption baseTokenOption = coinPairBean.baseTokenOption;
                    if (baseTokenOption != null) {
                        if (baseTokenOption.dataCategory == 0) {
                            coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_OPTION);
                        } else {
                            coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_OPTION_CATEGORY);
                        }

                        String quoteToken = coinPairBean.getQuoteTokenId();
                        currentExchangeId = coinPairBean.getExchangeId();
                        if (tabMap.containsKey(quoteToken)) {
                            QuoteTokensBean.TokenItem tabTokenItem = tabMap.get(quoteToken);
                            if (tabTokenItem != null) {
                                HashMap<String, CoinPairBean> coinPairMap = tabTokenItem.getCoinPairMap();
                                coinPairMap.put(coinPairBean.getBaseTokenId(), coinPairBean);
                            }
                        } else {
                            DebugLog.w("market", quoteToken + " tab is null");
                        }
                    }
                } else if (mTradeType == ContractTradeFragment.TAB_FUTURES) {
                    coinPairBean.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_FUTURES);
                    String tabId = coinPairBean.getFirstLevelUnderlyingId();
                    currentExchangeId = coinPairBean.getExchangeId();
                    if (tabMap.containsKey(tabId)) {
                        QuoteTokensBean.TokenItem tabTokenItem = tabMap.get(tabId);
                        if (tabTokenItem != null) {
                            HashMap<String, CoinPairBean> coinPairMap = tabTokenItem.getCoinPairMap();
                            coinPairMap.put(coinPairBean.getBaseTokenId(), coinPairBean);
                        }
                    } else {
                        DebugLog.w("market", tabId + " tab is null");
                    }
                }
            }

            notifyCoinPairListDataChange(tabMap);
        }
    }

//    /**
//     * APP首次打开提示交易界面使用的默认币对
//     * @param coinPairList
//     */
//    private void notifyTradeCoinPair(List<CoinPairBean> coinPairList) {
//        if (isSendDefaultCoinPair) {
//            return;
//        }
//        if (coinPairList.size() > 0) {
//            CoinPairBean coinPairBean = coinPairList.get(0);
//            coinPairBean.setNeedSwitchTradeTab(false);
//            EventBus.getDefault().postSticky(coinPairBean);
//            isSendDefaultCoinPair = true;
////            ToastUtils.showShort("HOME Post");
//        }
//
//    }

    /**
     * 提示币对数据更新
     *
     * @param tabMap
     */
    private void notifyCoinPairListDataChange(HashMap<String, QuoteTokensBean.TokenItem> tabMap) {
        String currentTabId = getCurrentTabId();
        QuoteTokensBean.TokenItem tokenItem = tabMap.get(currentTabId);

        if (tokenItem != null) {
            HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
            List<CoinPairBean> coinPairList = new ArrayList<>();
            for (String key : coinPairMap.keySet()) {
                CoinPairBean coinPairBean = coinPairMap.get(key);
                coinPairList.add(coinPairBean);
            }

            if (filterList != null && filterList.size() > 0)
                showMarket(filterList);
            else
                showMarket(coinPairList);
        }
    }

    private void showMarket(List<CoinPairBean> coinPairList) {
        /** TODO 期权主板 创新板特殊处理  ***********************/
        //期权分类
        HashMap<String, OptionCategoryBean> optionCategoryMap = SymbolDataManager.GetInstance().getOptionCategoryMap();
        for (String key : optionCategoryMap.keySet()) {
            optionCategoryMap.get(key).getCoinPairList().clear();
        }

        boolean isOption = false;
        if (coinPairList != null && coinPairList.size() > 0) {
            for (int i = 0; i < coinPairList.size(); i++) {
                CoinPairBean coinPairBean = coinPairList.get(i);
                if (coinPairBean.baseTokenOption != null) {
                    isOption = true;
                    String firstLevelUnderlyingId = coinPairBean.getFirstLevelUnderlyingId();
                    OptionCategoryBean optionCategory = SymbolDataManager.GetInstance().getOptionCategoryMap(firstLevelUnderlyingId);
                    if (optionCategory != null) {
                        List<CoinPairBean> coinPairList1 = optionCategory.getCoinPairList();
                        if (coinPairList1 != null) {
                            coinPairList1.add(coinPairBean);
                        }
                    }
                }
            }
        }

        if (isOption) {
            coinPairList.clear();
            for (String key : optionCategoryMap.keySet()) {
                OptionCategoryBean optionCategoryBean = optionCategoryMap.get(key);
                if (optionCategoryBean != null) {
                    List<CoinPairBean> coinPairList1 = optionCategoryBean.getCoinPairList();
                    if (coinPairList1 != null && coinPairList1.size() > 0) {
                        //添加主板信息
                        CoinPairBean coinPairBean1 = new CoinPairBean();
                        coinPairBean1.setCoinType(COIN_TYPE.COIN_TYPE_OPTION.getCoinType());
                        coinPairBean1.setItemShowType(MarketListMultiAdapter.ITEM_TYPE_OPTION_CATEGORY);
                        CoinPairBean.BaseTokenOption baseTokenOption1 = new CoinPairBean.BaseTokenOption();
                        baseTokenOption1.dataCategory = 1;
                        baseTokenOption1.categoryName = optionCategoryBean.getName();
                        coinPairBean1.baseTokenOption = baseTokenOption1;
                        coinPairList.add(coinPairBean1);
                        //添加主板下对应的币对
                        coinPairList.addAll(coinPairList1);
                    }
                }
            }
        }

        mData = coinPairList;
        if (!isTouching) {

            if (adapter != null) {
                adapter.setNewData(coinPairList);
                return;
            }
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            View emptyView = layoutInflater.inflate(R.layout.empty_layout, rootView, false);
//        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
//        layoutParams.height = PixelUtils.dp2px(getHeight());
//        emptyView.setLayoutParams(layoutParams);
            emptyView.findViewById(R.id.empty_txt).setOnClickListener(this);
            emptyView.findViewById(R.id.empty_img).setOnClickListener(this);

            adapter = new MarketListMultiAdapter(getActivity(), coinPairList, true, mSymbolId,this);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    List<CoinPairBean> data = adapter.getData();
                    CoinPairBean itemModel = data.get(position);
                    CoinPairBean.BaseTokenOption baseTokenOption = itemModel.baseTokenOption;
                    FuturensBaseToken baseTokenFutures = itemModel.baseTokenFutures;
                    if (mTradeType == ContractTradeFragment.TAB_OPTION) {
                        if (baseTokenOption != null) {
                            if (baseTokenOption.dataCategory == 0) {
                                //来自交易界面
                                itemModel.setBuyMode(true);
                                itemModel.setNeedSwitchTradeTab(true);
                                //IntentUtils.goTrade(mContext, itemModel);
                                EventBus.getDefault().postSticky(itemModel);
                                closePop(true);
                            }
                        }
                    } else if (mTradeType == ContractTradeFragment.TAB_FUTURES) {
                        if (baseTokenFutures != null) {
                            //来自交易界面
                            itemModel.setBuyMode(true);
                            itemModel.setNeedSwitchTradeTab(true);
                            EventBus.getDefault().postSticky(itemModel);
                            closePop(true);
                        }
                    }
                }
            });
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    List<CoinPairBean> data = adapter.getData();
                    CoinPairBean itemModel = data.get(position);
                    CoinPairBean.BaseTokenOption baseTokenOption = itemModel.baseTokenOption;
                    FuturensBaseToken baseTokenFutures = itemModel.baseTokenFutures;

                    if (mTradeType == ContractTradeFragment.TAB_OPTION) {
                        if (baseTokenOption != null) {
                            if (baseTokenOption.dataCategory == 0) {
                                //来自交易界面
                                itemModel.setBuyMode(true);
                                itemModel.setNeedSwitchTradeTab(true);
                                //IntentUtils.goTrade(mContext, itemModel);
                                EventBus.getDefault().postSticky(itemModel);
                                closePop(true);
                            }
                        }
                    } else if (mTradeType == ContractTradeFragment.TAB_FUTURES) {
                        if (baseTokenFutures != null) {
                            //来自交易界面
                            itemModel.setBuyMode(true);
                            itemModel.setNeedSwitchTradeTab(true);
                            EventBus.getDefault().postSticky(itemModel);
                            closePop(true);
                        }
                    }
                }
            });

//            adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
            //adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            //recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(adapter);
            adapter.setEmptyView(emptyView);
        }
    }


    public void changePage(String tabId) {
        notifyCoinPairListDataChange(tabMap);
    }

}



